﻿// SilverlightBridge
// Copyright (c) 2009
// by OpenLight Group
// http://openlightgroup.net/
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated 
// documentation files (the "Software"), to deal in the Software without restriction, including without limitation 
// the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and 
// to permit persons to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or substantial portions 
// of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED 
// TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL 
//
// CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER 
// DEALINGS IN THE SOFTWARE.

using System.Collections.Generic;
using System.Linq;
using System.Web.Services;
using System.IO;
using System;

namespace SilverlightFileManager
{
    [WebService(Namespace = "http://SilverlightDesktop.net/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    public class WebService : System.Web.Services.WebService
    {
        List<int> colProcessedCategoryIDs;

        #region WhoIAm
        [WebMethod(Description = "WhoIAm")]
        public UserInfo WhoIAm(int PortalID, int ModuleId, int UserID, string Password)
        {
            string strIPAddress = this.Context.Request.UserHostAddress;
            SilverlightBridgeAuthendicationHeader SilverlightBridgeAuthendicationHeader = new SilverlightBridgeAuthendicationHeader();
            SilverlightBridgeAuthendicationHeader.PortalID = PortalID;
            SilverlightBridgeAuthendicationHeader.ModuleId = ModuleId;
            SilverlightBridgeAuthendicationHeader.UserID = UserID;
            SilverlightBridgeAuthendicationHeader.Password = Password;
            SilverlightBridgeAuthendicationHeader.IPAddress = strIPAddress;

            UserInfo response = new UserInfo();

            Authendication Authendication = new Authendication(SilverlightBridgeAuthendicationHeader);
            if (Authendication.IsUserValid())
            {
                response = Authendication.GetUserInfo();
            }
            else
            {
                response.UserID = -1;
                response.FirstName = "Visitor";
                response.LastName = DateTime.Now.ToLongDateString();
            }

            return response;
        }
        #endregion

        // Folders

        #region GetFolders
        [WebMethod]
        public List<Folder> GetFolders(int FolderID, int PortalID, int ModuleId, int UserID, string Password)
        {
            List<Folder> colFolders = new List<Folder>();

            string strIPAddress = this.Context.Request.UserHostAddress;
            SilverlightBridgeAuthendicationHeader SilverlightBridgeAuthendicationHeader = new SilverlightBridgeAuthendicationHeader();
            SilverlightBridgeAuthendicationHeader.PortalID = PortalID;
            SilverlightBridgeAuthendicationHeader.ModuleId = ModuleId;
            SilverlightBridgeAuthendicationHeader.UserID = UserID;
            SilverlightBridgeAuthendicationHeader.Password = Password;
            SilverlightBridgeAuthendicationHeader.IPAddress = strIPAddress;

            Authendication Authendication = new Authendication(SilverlightBridgeAuthendicationHeader);
            if (Authendication.IsUserValid())
            {
                SilverlightFileManagerDALDataContext SilverlightFileManagerDALDataContext = new SilverlightFileManagerDALDataContext();
                IQueryable<FileUpload_Category> colFileUpload_Categories;

                // If FolderID = 0 then the ParentCategoryID is null
                // In the database a null CategoryID is the root folder
                if (FolderID == 0)
                {
                    colFileUpload_Categories = from FileUpload_Categories in SilverlightFileManagerDALDataContext.FileUpload_Categories
                                               where FileUpload_Categories.UserID == UserID
                                               where FileUpload_Categories.ParentCategoryID == null
                                               orderby FileUpload_Categories.CategoryName
                                               select FileUpload_Categories;
                }
                else
                {
                    colFileUpload_Categories = from FileUpload_Categories in SilverlightFileManagerDALDataContext.FileUpload_Categories
                                               where FileUpload_Categories.UserID == UserID
                                               where FileUpload_Categories.ParentCategoryID == FolderID
                                               orderby FileUpload_Categories.CategoryName
                                               select FileUpload_Categories;
                }

                foreach (var Category in colFileUpload_Categories.ToList())
                {
                    // If the Parent category is null it means that this is the Root Folder
                    // Create the "Local" option
                    if (Category.ParentCategoryID == null)
                    {
                        Folder objMyComputer = new Folder();
                        objMyComputer.FolderID = -1;
                        objMyComputer.FolderName = "Local";
                        objMyComputer.isLocal = true;
                        colFolders.Add(objMyComputer);
                    }

                    Folder objFolder = new Folder();
                    objFolder.FolderID = Category.CategoryID;
                    objFolder.ParentFolderID = FolderID;
                    objFolder.FolderName = Category.CategoryName;
                    objFolder.isLocal = false;

                    // Get sub folders
                    var colSubFolders = from FileUpload_Categories in SilverlightFileManagerDALDataContext.FileUpload_Categories
                                        where FileUpload_Categories.ParentCategoryID == Category.CategoryID
                                        orderby FileUpload_Categories.CategoryName
                                        select FileUpload_Categories;

                    foreach (var SubFolder in colSubFolders)
                    {
                        Folder objSubFolder = new Folder();
                        objSubFolder.FolderID = SubFolder.CategoryID;
                        objSubFolder.ParentFolderID = Category.CategoryID;
                        objSubFolder.FolderName = SubFolder.CategoryName;
                        objSubFolder.isLocal = false;

                        objFolder.SubFolders.Add(objSubFolder);
                    }

                    colFolders.Add(objFolder);
                }
            }

            return colFolders;
        }
        #endregion

        #region AddFolder
        [WebMethod]
        public Folder AddFolder(int PortalID, int ModuleId, int UserID, string Password, int FolderID, string FolderName)
        {
            Folder response = new Folder();

            string strIPAddress = this.Context.Request.UserHostAddress;

            SilverlightBridgeAuthendicationHeader SilverlightBridgeAuthendicationHeader = new SilverlightBridgeAuthendicationHeader();
            SilverlightBridgeAuthendicationHeader.PortalID = PortalID;
            SilverlightBridgeAuthendicationHeader.ModuleId = ModuleId;
            SilverlightBridgeAuthendicationHeader.UserID = UserID;
            SilverlightBridgeAuthendicationHeader.Password = Password;
            SilverlightBridgeAuthendicationHeader.IPAddress = strIPAddress;

            Authendication Authendication = new Authendication(SilverlightBridgeAuthendicationHeader);
            if (Authendication.IsUserValid())
            {
                SilverlightFileManagerDALDataContext SilverlightFileManagerDALDataContext = new SilverlightFileManagerDALDataContext();

                // Get an instance of the parent Folder
                var objFolder = (from FileUpload_Categories in SilverlightFileManagerDALDataContext.FileUpload_Categories
                                 where FileUpload_Categories.CategoryID == FolderID
                                 where FileUpload_Categories.UserID == UserID
                                 select FileUpload_Categories).FirstOrDefault();

                if (objFolder != null)
                {
                    // Add Folder
                    FileUpload_Category objNewFileUpload_Category = new FileUpload_Category();
                    objNewFileUpload_Category.CategoryName = FolderName;
                    objNewFileUpload_Category.Level = objFolder.Level + 1;
                    objNewFileUpload_Category.ParentCategoryID = objFolder.CategoryID;
                    objNewFileUpload_Category.PortalID = objFolder.PortalID;
                    objNewFileUpload_Category.UserID = UserID;

                    SilverlightFileManagerDALDataContext.FileUpload_Categories.InsertOnSubmit(objNewFileUpload_Category);
                    SilverlightFileManagerDALDataContext.SubmitChanges();

                    Folder objNewFolder = new Folder();
                    objNewFolder.FolderID = objNewFileUpload_Category.CategoryID;
                    objNewFolder.ParentFolderID = objNewFileUpload_Category.ParentCategoryID ?? 0;
                    objNewFolder.FolderName = FolderName.Trim();

                    response = objNewFolder;
                }
            }

            return response;
        }
        #endregion

        #region DeleteFolder
        [WebMethod]
        public int DeleteFolder(int PortalID, int ModuleId, int UserID, string Password, int FolderID)
        {
            int response = -1;

            string strIPAddress = this.Context.Request.UserHostAddress;

            SilverlightBridgeAuthendicationHeader SilverlightBridgeAuthendicationHeader = new SilverlightBridgeAuthendicationHeader();
            SilverlightBridgeAuthendicationHeader.PortalID = PortalID;
            SilverlightBridgeAuthendicationHeader.ModuleId = ModuleId;
            SilverlightBridgeAuthendicationHeader.UserID = UserID;
            SilverlightBridgeAuthendicationHeader.Password = Password;
            SilverlightBridgeAuthendicationHeader.IPAddress = strIPAddress;

            Authendication Authendication = new Authendication(SilverlightBridgeAuthendicationHeader);
            if (Authendication.IsUserValid())
            {
                SilverlightFileManagerDALDataContext SilverlightFileManagerDALDataContext = new SilverlightFileManagerDALDataContext();

                // Get an instance of the Folder
                var objFolder = (from FileUpload_Categories in SilverlightFileManagerDALDataContext.FileUpload_Categories
                                 where FileUpload_Categories.CategoryID == FolderID
                                 where FileUpload_Categories.UserID == UserID
                                 select FileUpload_Categories).FirstOrDefault();

                if (objFolder != null)
                {
                    // Make a Temp object to use to update the child nodes
                    FileUpload_Category TmpFileUpload_Category = new FileUpload_Category();
                    TmpFileUpload_Category.CategoryID = objFolder.CategoryID;
                    if (objFolder.ParentCategoryID == null)
                    {
                        TmpFileUpload_Category.Level = 0;
                    }
                    else
                    {
                        TmpFileUpload_Category.Level = GetLevelOfParent(objFolder.ParentCategoryID);
                    }

                    // ** Delete all files in the Node **
                    // Get files in Folder
                    var colFilesInFolder = from FileUpload_Files in SilverlightFileManagerDALDataContext.FileUpload_Files
                                           where FileUpload_Files.FolderID == TmpFileUpload_Category.CategoryID
                                           select FileUpload_Files;

                    // Loop thru each item
                    foreach (var objFile in colFilesInFolder)
                    {
                        DeleteFileFromFolder(objFile.FileID);
                    }

                    // Delete the node
                    SilverlightFileManagerDALDataContext.FileUpload_Categories.DeleteOnSubmit(objFolder);
                    SilverlightFileManagerDALDataContext.SubmitChanges();

                    // Update levels of all the Children   
                    UpdateLevelOfChildren(TmpFileUpload_Category);

                    // Update all the children nodes to give them a new parent
                    var CategoryChildren = from FileUpload_Categories in SilverlightFileManagerDALDataContext.FileUpload_Categories
                                           where FileUpload_Categories.ParentCategoryID == objFolder.CategoryID
                                           select FileUpload_Categories;

                    // Loop thru each item
                    foreach (var objCategory in CategoryChildren)
                    {
                        objCategory.ParentCategoryID = objFolder.ParentCategoryID;
                        SilverlightFileManagerDALDataContext.SubmitChanges();
                    }

                    response = FolderID;
                }
            }

            return response;
        }

        #region DeleteFileFromFolder
        private void DeleteFileFromFolder(int intFileID)
        {
            SilverlightFileManagerDALDataContext SilverlightFileManagerDALDataContext = new SilverlightFileManagerDALDataContext();

            var objFileUpload_Files = (from FileUpload_Files in SilverlightFileManagerDALDataContext.FileUpload_Files
                                       where FileUpload_Files.FileID == intFileID
                                       select FileUpload_Files).FirstOrDefault();

            // Delete file
            if (objFileUpload_Files != null)
            {
                string filePath = Path.Combine(objFileUpload_Files.FilePath, objFileUpload_Files.FileName);
                FileInfo fi = new FileInfo(filePath);
                if (fi.Exists)
                {
                    fi.Delete();
                }
            }

            // Delete from database
            SilverlightFileManagerDALDataContext.FileUpload_Files.DeleteOnSubmit(objFileUpload_Files);
            SilverlightFileManagerDALDataContext.SubmitChanges();
        }
        #endregion

        #region UpdateLevelOfChildren
        private void UpdateLevelOfChildren(FileUpload_Category result)
        {
            int? intStartingLevel = result.Level;

            if (colProcessedCategoryIDs == null)
            {
                colProcessedCategoryIDs = new List<int>();
            }

            SilverlightFileManagerDALDataContext SilverlightFileManagerDALDataContext = new SilverlightFileManagerDALDataContext();

            // Get the children of the current item
            // This method may be called from the top level or recuresively by one of the child items
            var CategoryChildren = from FileUpload_Categories in SilverlightFileManagerDALDataContext.FileUpload_Categories
                                   where FileUpload_Categories.ParentCategoryID == result.CategoryID
                                   select FileUpload_Categories;

            // Loop thru each item
            foreach (var objCategory in CategoryChildren)
            {
                if (!colProcessedCategoryIDs.Contains(objCategory.CategoryID))
                {
                    colProcessedCategoryIDs.Add(objCategory.CategoryID);

                    objCategory.Level = ((intStartingLevel) ?? 0) + 1;
                    SilverlightFileManagerDALDataContext.SubmitChanges();

                    //Recursively call the UpdateLevelOfChildren method adding all children
                    UpdateLevelOfChildren(objCategory);
                }
            }
        }
        #endregion

        #region GetLevelOfParent
        private int GetLevelOfParent(int? ParentCategoryID)
        {
            SilverlightFileManagerDALDataContext SilverlightFileManagerDALDataContext = new SilverlightFileManagerDALDataContext();

            var result = (from FileUpload_Categories in SilverlightFileManagerDALDataContext.FileUpload_Categories
                          where FileUpload_Categories.CategoryID == ParentCategoryID
                          select FileUpload_Categories).FirstOrDefault();

            return (result == null) ? 0 : result.Level;
        }
        #endregion

        #endregion

        #region UpdateFolder
        [WebMethod]
        public string UpdateFolder(int PortalID, int ModuleId, int UserID, string Password, int FolderID, string FolderName)
        {
            string response = "";
            string strIPAddress = this.Context.Request.UserHostAddress;

            SilverlightBridgeAuthendicationHeader SilverlightBridgeAuthendicationHeader = new SilverlightBridgeAuthendicationHeader();
            SilverlightBridgeAuthendicationHeader.PortalID = PortalID;
            SilverlightBridgeAuthendicationHeader.ModuleId = ModuleId;
            SilverlightBridgeAuthendicationHeader.UserID = UserID;
            SilverlightBridgeAuthendicationHeader.Password = Password;
            SilverlightBridgeAuthendicationHeader.IPAddress = strIPAddress;

            Authendication Authendication = new Authendication(SilverlightBridgeAuthendicationHeader);
            if (Authendication.IsUserValid())
            {
                SilverlightFileManagerDALDataContext SilverlightFileManagerDALDataContext = new SilverlightFileManagerDALDataContext();

                // Get an instance of the Folder
                var objFolder = (from FileUpload_Categories in SilverlightFileManagerDALDataContext.FileUpload_Categories
                                 where FileUpload_Categories.CategoryID == FolderID
                                 where FileUpload_Categories.UserID == UserID
                                 select FileUpload_Categories).FirstOrDefault();

                if (objFolder != null)
                {
                    // Set Folder name to the existing name in case the new name is blank
                    response = FolderName;
                    if (FolderName.Trim() != "")
                    {
                        // Update Folder Name
                        objFolder.CategoryName = FolderName;
                        SilverlightFileManagerDALDataContext.SubmitChanges();
                    }
                }
            }

            return response;
        }
        #endregion

        // Files

        #region GetFiles
        [WebMethod]
        public List<SilverlightFile> GetFiles(int FolderID, int PortalID, int ModuleId, int UserID, string Password)
        {
            List<SilverlightFile> colFiles = new List<SilverlightFile>();

            string strIPAddress = this.Context.Request.UserHostAddress;
            SilverlightBridgeAuthendicationHeader SilverlightBridgeAuthendicationHeader = new SilverlightBridgeAuthendicationHeader();
            SilverlightBridgeAuthendicationHeader.PortalID = PortalID;
            SilverlightBridgeAuthendicationHeader.ModuleId = ModuleId;
            SilverlightBridgeAuthendicationHeader.UserID = UserID;
            SilverlightBridgeAuthendicationHeader.Password = Password;
            SilverlightBridgeAuthendicationHeader.IPAddress = strIPAddress;

            Authendication Authendication = new Authendication(SilverlightBridgeAuthendicationHeader);
            if (Authendication.IsUserValid())
            {
                SilverlightFileManagerDALDataContext SilverlightFileManagerDALDataContext = new SilverlightFileManagerDALDataContext();

                var ColSilverlightFiles = from SilverlightFiles in SilverlightFileManagerDALDataContext.FileUpload_Files
                                          where SilverlightFiles.FolderID == FolderID
                                          select SilverlightFiles;

                // Get Files
                if (ColSilverlightFiles != null)
                {
                    foreach (var objFile in ColSilverlightFiles)
                    {
                        SilverlightFile objSilverlightFile = new SilverlightFile();
                        objSilverlightFile.FileName = objFile.OriginalFileName;
                        objSilverlightFile.FolderID = objFile.FolderID;
                        objSilverlightFile.FileID = objFile.FileID;
                        objSilverlightFile.isLocal = false;
                        colFiles.Add(objSilverlightFile);
                    }
                }

            }

            return colFiles;
        }
        #endregion

        #region DeleteFile
        [WebMethod]
        public int DeleteFile(int PortalID, int ModuleId, int UserID, string Password, int FileID)
        {
            int response = -1;

            string strIPAddress = this.Context.Request.UserHostAddress;

            SilverlightBridgeAuthendicationHeader SilverlightBridgeAuthendicationHeader = new SilverlightBridgeAuthendicationHeader();
            SilverlightBridgeAuthendicationHeader.PortalID = PortalID;
            SilverlightBridgeAuthendicationHeader.ModuleId = ModuleId;
            SilverlightBridgeAuthendicationHeader.UserID = UserID;
            SilverlightBridgeAuthendicationHeader.Password = Password;
            SilverlightBridgeAuthendicationHeader.IPAddress = strIPAddress;

            Authendication Authendication = new Authendication(SilverlightBridgeAuthendicationHeader);
            if (Authendication.IsUserValid())
            {
                SilverlightFileManagerDALDataContext SilverlightFileManagerDALDataContext = new SilverlightFileManagerDALDataContext();

                var objFileUpload_Files = (from FileUpload_Files in SilverlightFileManagerDALDataContext.FileUpload_Files
                                           where FileUpload_Files.UserID == UserID
                                           where FileUpload_Files.FileID == FileID
                                           select FileUpload_Files).FirstOrDefault();

                // Delete file
                if (objFileUpload_Files != null)
                {
                    string filePath = Path.Combine(objFileUpload_Files.FilePath, objFileUpload_Files.FileName);
                    FileInfo fi = new FileInfo(filePath);
                    if (fi.Exists)
                    {
                        fi.Delete();

                        // Delete from database
                        SilverlightFileManagerDALDataContext.FileUpload_Files.DeleteOnSubmit(objFileUpload_Files);
                        SilverlightFileManagerDALDataContext.SubmitChanges();

                        // Success
                        response = 0;
                    }
                }
            }

            return response;
        }
        #endregion

        #region UpdateFileFolder
        [WebMethod]
        public string UpdateFileFolder(int PortalID, int ModuleId, int UserID, string Password, int FolderID, int FileID)
        {
            string response = "";
            string strIPAddress = this.Context.Request.UserHostAddress;

            SilverlightBridgeAuthendicationHeader SilverlightBridgeAuthendicationHeader = new SilverlightBridgeAuthendicationHeader();
            SilverlightBridgeAuthendicationHeader.PortalID = PortalID;
            SilverlightBridgeAuthendicationHeader.ModuleId = ModuleId;
            SilverlightBridgeAuthendicationHeader.UserID = UserID;
            SilverlightBridgeAuthendicationHeader.Password = Password;
            SilverlightBridgeAuthendicationHeader.IPAddress = strIPAddress;

            Authendication Authendication = new Authendication(SilverlightBridgeAuthendicationHeader);
            if (Authendication.IsUserValid())
            {
                // Get an instance of the File
                SilverlightFileManagerDALDataContext SilverlightFileManagerDALDataContext = new SilverlightFileManagerDALDataContext();

                var objFileUpload_Files = (from FileUpload_Files in SilverlightFileManagerDALDataContext.FileUpload_Files
                                           where FileUpload_Files.UserID == UserID
                                           where FileUpload_Files.FileID == FileID
                                           select FileUpload_Files).FirstOrDefault();

                if (objFileUpload_Files != null)
                {
                    // Update File
                    objFileUpload_Files.FolderID = FolderID;
                    SilverlightFileManagerDALDataContext.SubmitChanges();

                    // Set the response to be the new Folder so the 
                    // Silverlight FileManager will know what folder to now show
                    response = FolderID.ToString();
                }
            }

            return response;
        }
        #endregion

        // Out Of Browser web methods

        #region GetOOBPassword
        [WebMethod(Description = "GetOOBPassword")]
        public string GetOOBPassword(int PortalID, int ModuleId, string UserName, string Password)
        {
            string OOBPassword = "";

            SilverlightFileManagerDALDataContext SilverlightFileManagerDALDataContext = new SilverlightFileManagerDALDataContext();
            var SilverlightBridgeUser = (from SilverlightBridgeUsers in SilverlightFileManagerDALDataContext.SilverlightBridgeUsers
                                         where SilverlightBridgeUsers.UserName == UserName
                                         where SilverlightBridgeUsers.Password == Password
                                         select SilverlightBridgeUsers).FirstOrDefault();

            if (SilverlightBridgeUser != null)
            {
                Utility objUtility = new Utility();
                OOBPassword = objUtility.GetRandomPassword();
                SilverlightBridgeUser.SilverlightOOBPassword = OOBPassword;
                SilverlightFileManagerDALDataContext.SubmitChanges();
                OOBPassword = SilverlightBridgeUser.UserID.ToString() + "_" + OOBPassword;
            }

            return OOBPassword;
        }
        #endregion

        #region GetOOBRootServerFolder
        [WebMethod]
        public int GetOOBRootServerFolderID(int PortalID, int ModuleId, int UserID, string Password)
        {
            int intRootFolderID = 0;

            string strIPAddress = this.Context.Request.UserHostAddress;
            SilverlightBridgeAuthendicationHeader SilverlightBridgeAuthendicationHeader = new SilverlightBridgeAuthendicationHeader();
            SilverlightBridgeAuthendicationHeader.PortalID = PortalID;
            SilverlightBridgeAuthendicationHeader.ModuleId = ModuleId;
            SilverlightBridgeAuthendicationHeader.UserID = UserID;
            SilverlightBridgeAuthendicationHeader.Password = Password;
            SilverlightBridgeAuthendicationHeader.IPAddress = strIPAddress;

            Authendication Authendication = new Authendication(SilverlightBridgeAuthendicationHeader);
            if (Authendication.IsUserValid())
            {
                SilverlightFileManagerDALDataContext SilverlightFileManagerDALDataContext = new SilverlightFileManagerDALDataContext();

                var RootFolder = (from FileUpload_Categories in SilverlightFileManagerDALDataContext.FileUpload_Categories
                                  where FileUpload_Categories.UserID == UserID
                                  where FileUpload_Categories.ParentCategoryID == null
                                  orderby FileUpload_Categories.CategoryName
                                  select FileUpload_Categories).FirstOrDefault();

                intRootFolderID = RootFolder.CategoryID;
            }

            return intRootFolderID;
        }
        #endregion
    }
}
